"""
@name : 2.上下文管理器异常处理
@author : wenyao
@projectname: sanchuanglianxi
"""

#__exit__三个参数   异常类，异常值，回溯信息
#上下文管理器，传播异常，终止异常

# class BubbleExcetion(object):
#     def __enter__(self):
#         return self
#
#     def __exit__(self, exc_type, exc_val, exc_tb):
#         if exc_val:
#             print(f"Bubbling up excetion: {exc_val}")
#         return False   #传播异常
#         #return True    #终止异常
#
#return True
#类似
# try:
#     do_sth
# except:
#     do_sth

# with BubbleExcetion():
#     print(1+1)
#
# with BubbleExcetion():
#     print(1/0)
#
# print("test bubbleexcetion")

#上下文管理器，处理指定异常,子类异常也会捕获
class ValueErrorSubclass(ValueError):
    pass

# class HandleValueError():
#     def __init__(self):
#         self.name = "wen"
#
#     def __enter__(self):
#         #pass
#         return self
#
#     def __exit__(self, exc_type, exc_value, exc_tb):
#         if not exc_type:
#             return True
#         if issubclass(exc_type, ValueError):
#             print(f"Handling ValueError:{exc_value}")
#             return True
#
#         #其他错误传递下去
#         return False

# with HandleValueError():
#     print(1/0)

# with HandleValueError() as h:
#     print(h.name)
#     raise ValueError("value error")
#
# with HandleValueError() as h:
#         print(h.name)
#         raise ValueErrorSubclass("value error subclass")

#上下文管理器波或一个给定的异常，但不希望显示的捕获它的子类

class HandleValueError():
    def __init__(self):
        self.name = "wen"

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_tb):
        if not exc_type:
            return True
        #if issubclass(exc_type, ValueError):
        if exc_type == ValueError:
            print(f"Handling ValueError:{exc_value}")
            return True

        #其他错误传递下去
        return False

with HandleValueError():
    #print(h.name)
    raise ValueError("value error")
#
# print("this is end.....")
#
# with HandleValueError() as h:
#         print(h.name)
#         raise ValueErrorSubclass("value error subclass")
# try:
#    1/0
# except:
#     print("test")
# print("this is value error sub class")


